﻿using Microsoft.Extensions.Logging;
using Simple.Tools;
using SimpleNet.Net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

/*********************************************************
 * 命名空间 Simple.BasicNet.Core.Net
 * 接口名称 ConnectionContext
 * 开发人员：11920
 * 创建时间：2023/4/7 10:11:00
 * 描述说明：
 * 更改历史：
 * 
 * *******************************************************/
namespace SimpleNet.Handle
{
	public class Context : IContext, IDisposable
	{
		[Autowired]
		protected ILogger<IContext> logger { get; set; }

		[Autowired]
		protected IClientManager clients { get; set; }
		public Context() { }	
		public IDataPack CurrentPack { get { return currentPack; } set { currentPack = value; } }
		public long ConnectionId { get { return connectionId; } set { connectionId = value; } }

		private Socket client;

		public void SetClient(Socket socket)
		{
			if (ToolSimpleCheck.IsNull(client))
			{
				ToolSimpleCheck.IsNullThrowException(socket);
				if (socket.Connected)
				{
					client = socket;
				}
				else
				{
					logger.LogWarning($"Id:{connectionId} 断开连接!");
				}
			}
		}

		private IDataPack currentPack;
		private long connectionId;
		public async Task SendAsync(byte[] buffer, SocketFlags socketFlags, CancellationToken cancellationToken = default)
		{
			//send.Invoke(bytes);

			try
			{
				if (client.Connected)
				{
					//logger.LogWarning(client.Connected.ToString() + "数据返回成功!");
					await client.SendAsync(buffer, socketFlags, cancellationToken);
				}
				else
				{
					logger.LogWarning(client.Connected.ToString() + "发送失败,连接断开!");
				}
				//if (client.Connected)
			}
			catch (Exception ex)
			{
				logger.LogError(ex.Message);
				if (ex.InnerException != null)
				{
					logger.LogError(ex.InnerException.Message);
				}
				Dispose();
			}
		}


		public void Send(byte[] buffer)
			{
				//send.Invoke(bytes);

				try
				{
					if (client.Connected)
					{
						//logger.LogWarning(client.Connected.ToString() + "数据返回成功!");
						client.Send(buffer);
					}
					else
					{
						logger.LogWarning(client.Connected.ToString() + "发送失败,连接断开!");
					    Dispose();
				}
					//if (client.Connected)
				}
				catch (Exception ex)
				{
					logger.LogError(ex.Message);
					if (ex.InnerException != null)
					{
						logger.LogError(ex.InnerException.Message);
					}
					Dispose();
				}
			}


		public void SendUTF8(string msg)
		{
			Send(Encoding.UTF8.GetBytes(msg));
		}

		public async Task SendUTF8Async(string msg,SocketFlags socketFlags,CancellationToken cancellationToken=default)
		{
			await SendAsync(Encoding.UTF8.GetBytes(msg), socketFlags, cancellationToken);
		}
		public void SendASCII(string msg)
		{
			Send(Encoding.ASCII.GetBytes(msg));
		}

		public async Task SendASCIIAsync(string msg,SocketFlags socketFlags,CancellationToken cancellationToken = default)
		{
			await SendAsync(Encoding.ASCII.GetBytes(msg),socketFlags,cancellationToken);
		}

		public TContext GetContext<TContext>() where TContext : class,IContext 
		{
		   if(this is  TContext context)
			{
				return context;
			}
			return null;
		}

		public void Dispose()
		{
			if (clients!=null)
			{
				clients.RemoveClient(connectionId);
			}
		}
	}
}
